package com.atguigu.lease.web.app.service.impl;

import com.atguigu.lease.model.entity.BrowsingHistory;
import com.atguigu.lease.web.app.mapper.BrowsingHistoryMapper;
import com.atguigu.lease.web.app.service.BrowsingHistoryService;
import com.atguigu.lease.web.app.vo.history.HistoryItemVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * @author liubo
 * @description 针对表【browsing_history(浏览历史)】的数据库操作Service实现
 * @createDate 2023-07-26 11:12:39
 */
@Service
@Slf4j
public class BrowsingHistoryServiceImpl extends ServiceImpl<BrowsingHistoryMapper, BrowsingHistory>
        implements BrowsingHistoryService {
    @Resource
    private BrowsingHistoryMapper browsingHistoryMapper;


    @Override
    public IPage<HistoryItemVo> findHistoryItemVoPage(IPage<HistoryItemVo> page, Long userId) {
        return browsingHistoryMapper.findHistoryItemVoPage(page,userId);
    }

    //该方法用于实现保存用户的浏览记录
    @Override
    public void saveHistory(Long userId, Long id) {
        //1.创建浏览记录对象
        BrowsingHistory history = new BrowsingHistory();
        history.setUserId(userId);
        history.setRoomId(id);
        history.setBrowseTime(new Date());
        //2.去数据库中查询是否有过相同的记录，如果有，那么就覆盖这条记录
        QueryWrapper<BrowsingHistory> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(BrowsingHistory::getUserId, userId)
                .eq(BrowsingHistory::getRoomId, id);
        long count = this.count(queryWrapper);
        //3.如果这条记录存在，那么我们就覆盖这条记录，更新最新的浏览时间
        if (count > 0) {
            LambdaUpdateWrapper<BrowsingHistory> updateWrapper = new LambdaUpdateWrapper<>();
            updateWrapper.eq(BrowsingHistory::getUserId, userId);
            updateWrapper.eq(BrowsingHistory::getRoomId, id);
            this.update(history, updateWrapper);
        } else {
            //4.若不存在,那么插入这条数据
            this.save(history);
        }
    }

}




